import CreateForm from '@/pages/Admin/InterfaceInfo/List/components/CreateForm';
import {
  addInterfaceInfoUsingPost,
  deleteInterfaceInfoUsingPost,
  listInterfaceInfoVoByPageUsingPost,
  updateInterfaceInfoUsingPost,
} from '@/services/feiapi/interfaceInfoController';
import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {FooterToolbar, PageContainer, ProTable} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, message} from 'antd';
import React, {useRef, useState} from 'react';
import UpdateForm from './components/UpdateForm';
import {useModel} from "@@/exports";

/**
 * component
 * @constructor
 */
const AdminInterfaceInfoList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const actionCreateRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfoVO>();
  const [selectedRowsState, setSelectedRows] = useState<API.InterfaceInfoVO[]>([]);
  //获取当前登录的用户信息
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.InterfaceInfoAddRequest) => {
    const hide = message.loading('正在添加');
    try {
      const res = await addInterfaceInfoUsingPost({
        ...fields,
      });
      hide();
      message.success(res.message);
      return true;
    } catch (error: any) {
      hide();
      message.error(error.message);
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.InterfaceInfoUpdateRequest) => {
    const hide = message.loading('正在更新');
    try {
      const res = await updateInterfaceInfoUsingPost({
        ...fields,
      });
      hide();
      message.success(res.message);
      return true;
    } catch (error: any) {
      hide();
      message.error(error.message);
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param id
   */
  const handleRemove = async (id: API.DeleteRequest) => {
    const hide = message.loading('正在删除');
    try {
      const res = await deleteInterfaceInfoUsingPost({
        ...id,
      });
      hide();
      message.success(res.message);
      return true;
    } catch (error: any) {
      hide();
      message.error(error.message);
      return false;
    }
  };
  /**
   *  Delete node
   * @zh-CN 批量删除节点
   *
   * @param id
   */
  const handleRemoveBatch = async (ids: API.DeleteRequest[]) => {
    if (ids.length === 1) {
      await handleRemove(ids[0]);
      return true;
    }
    const hide = message.loading('正在删除');
    try {
      for (let i = 0; i < ids.length; i++) {
        await handleRemove(ids[i]);
      }
      hide();
      message.success('批量删除成功');
      return true;
    } catch (error: any) {
      hide();
      message.error(error.message);
      return false;
    }
  };

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const columns: ProColumns<API.InterfaceInfoVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
      hideInForm: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        required: true,
      },
    },
    {
      title: 'url',
      dataIndex: 'url',
      valueType: 'text',
      formItemProps: {
        required: true,
      },
    },
    {
      title: '方式',
      dataIndex: 'method',
      valueType: 'text',
      formItemProps: {
        required: true,
      },
      valueEnum: {
        GET: {
          text: 'GET',
          status: 'Default',
        },
        POST: {
          text: 'POST',
        },
        PUT: {
          text: 'PUT',
        },
        DELETE: {
          text: 'DELETE',
        },
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: '请求参数',
      dataIndex: 'params',
      valueType: 'jsonCode',
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: 'jsonCode',
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      valueType: 'jsonCode',
    },

    {
      title: '创建人id',
      dataIndex: 'userId',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'date',
      hideInForm: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '开启',
          status: 'Processing',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,
        <a
          key="delete"
          onClick={async () => {
            await handleRemove(record);
            setCurrentRow(undefined);
            actionRef.current?.reloadAndRest?.();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.InterfaceInfoVO, API.PageParams>
        headerTitle={'接口表格'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params: API.InterfaceInfoQueryRequest) => {
          try {
            const res = await listInterfaceInfoVoByPageUsingPost({
              ...params,
            });
            return {
              data: res?.data?.records,
              success: true,
              total: res?.data?.total,
            };
          } catch (e: any) {
            message.error(e.message);
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemoveBatch(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <CreateForm
        onCancel={() => {
          handleModalOpen(false);
          actionCreateRef.current?.reset?.();
        }}
        onSubmit={async (value) => {
          try {
            await handleAdd({
              'userId':currentUser?.id,
              ...value,
            });
            handleModalOpen(false);
            actionCreateRef.current?.reset?.();
          } catch (e: any) {
            message.error(e.message);
          }
        }}
        open={createModalOpen}
        columns={columns}
        actionRef={actionCreateRef}
      />
      <UpdateForm
        onCancel={() => {
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
        }}
        onSubmit={async (value) => {
          if (!currentRow){
            return;
          }
          try {
            await handleUpdate({
              id:currentRow.id,
              ...value,
            });
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          } catch (e: any) {
            message.error(e.message);
          }
        }}
        open={updateModalOpen}
        values={currentRow}
        columns={columns}
      />
    </PageContainer>
  );
};
export default AdminInterfaceInfoList;
